import { ref } from 'vue'
import { defineStore } from 'pinia'
import locaCache from '@/utils/locaCache'
import { accountLogin, getUserInfo } from '@/service/modules/login/login'
import { constRoute } from '@/router/routes'
import { CheckUser } from '@/types'
import { useRoute } from 'vue-router'
export const useLoginStore = defineStore('login', () => {
  const menuRoutes = ref<any[]>(constRoute)
  const token = ref<string>(locaCache.getLocalCache('token') ?? '')
  const userInfos = ref<CheckUser>(locaCache.getLocalCache('userInfos') ?? {})
  async function accountLoginAction(account: any) {
    const result = await accountLogin(account)
    // 登录成功
    if (result.code === 200) {
      // 存储token
      token.value = result.data.token
      locaCache.setLocalCache('token', result.data.token)
      return true
    } else {
      return false
    }
  }

  // 获取用户信息
  async function getUserInfoAction() {
    const result = await getUserInfo()
    // 获取成功
    if (result.code === 200) {
      userInfos.value = result.data.checkUser
      locaCache.setLocalCache('userInfo', result.data.checkUser)
    } else {
      return
    }
  }
  // 退出登录
  function clearUserInfo() {
    // 清空仓库
    userInfos.value = {}
    // 清空localhost
    locaCache.clearLocal()
  }

  return { token, menuRoutes, userInfos, accountLoginAction, getUserInfoAction, clearUserInfo }
})
